<?php

namespace app\uni\controller;

use think\Controller;

// 引入微信SDK
use EasyWeChat\Factory;

class Business extends Controller
{
    public function __construct(){
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->ProductModel = model('Order.Product');


        // 全局配置的微信的SDK
        $config = [
            'app_id' => 'wx9be9df1928a9eb4a', //appid
            'secret' => '220c02a606c40386af74789ca7b8c700', //AppSecret
            'response_type' => 'array', //调用微信接口返回什么类型数据（数组）

            // 日志
            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

        // 微信小程序SDK实例对象
        $this->app = Factory::miniProgram($config);
    }

    // 授权登录的方法
    public function login(){
        if ($this->request->isPost()){
            // 获取临时凭证
            $code =$this->request->param('code','','trim');

            if(empty($code)){
                $this->error('临时凭证获取失败');
                exit;
            }

            // 请求微信公众平台 换取openid 唯一标识符
            $wxauth = $this->app->auth->session($code);

            // 获取openid
            $openid = isset($wxauth['openid']) ? trim($wxauth['openid']) : '';

            if(empty($openid)){
                $this->error('授权openid失败');
                exit;
            }

            // 去business表中查找 openid 绑定记录
            $business = $this->BusinessModel->where(['openid'=>$openid])->find();

            if($business){
                // 有绑定的账号
                $this->success('授权登录成功',null,$business);
                exit;
            }else{
                // 没有绑定的账号
                $this->success('授权成功请绑定账号',null,['action'=>'bind','openid'=>$openid]);
                exit;
            }

        }
    }

    // 绑定账号的方法
    public function bind(){
        if($this->request->isAjax()){
            $mobile = $this->request->param("mobile", '', 'trim');
            $password = $this->request->param("password", '', 'trim');
            $openid = $this->request->param("openid", '', 'trim');

            if(empty($mobile)){
                $this->error('手机号码不能为空');
                exit;
            }

            if(empty($password)){
                $this->error('密码不能为空');
                exit;
            }

            if(empty($openid)){
                $this->error('oprnid不能为空');
                exit;
            }

            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if($business){
                // 能找到用户意味着 他在其他平台上注册过账号，目前是首次来到小程序
                // Update 更新语句 openid
                $result = $this->BusinessModel->where(['id' => $business['id']])->update(['openid' => $openid]);

                if($result === FALSE)
                {
                    $this->error('绑定账号失败');
                    exit;
                }

                //查询一遍最新的数据
                $business = $this->BusinessModel->find($business['id']);

                $this->success('绑定账号成功', null, $business);
                exit;
            }else{
                // 没有找到用户，意味着 他在其他平台上没有账号，首次来到小程序
                // Insert 插入语句 顺带将openid 也一并插入进去

                //生成一个密码盐
                $salt = randstr();

                //加密密码
                $password = md5($password.$salt);

                //组装数据
                $data = [
                    'openid' => $openid,
                    'mobile' => $mobile,
                    'nickname' => build_encrypt($mobile, 3, 4, '*'), //脱敏显示
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0', //性别
                    'deal' => '0', //成交状态
                    'money' => '0', //余额
                    'auth' => '0', //邮箱认证
                ];

                //查询出防伪查询的渠道来源的ID信息 数据库查询
                $data['sourceid'] = model('common/Business/Source')->where(['name'=>['LIKE', "%防伪查询%"]])->value('id');

                //执行插入 返回自增的条数
                $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                if($result === FALSE)
                {
                    //失败
                    $this->error($this->BusinessModel->getError());
                    exit;
                }else
                {
                    //查询出当前插入的数据记录
                    $business = $this->BusinessModel->find($this->BusinessModel->id);

                    //注册
                    $this->success('注册成功', null, $business);
                    exit;
                }
            }
        }
    }

    //解除绑定的方法
    public function unbind(){
        if($this->request->isPost()){
            $busid = $this->request->param('busid', 0, 'trim');

            // 查看用户是否存在
            $business = $this->BusinessModel->find($busid);

            if(!$business){
                $this->error('用户不存在');
                exit;
            }

            // 解除绑定
            $result= $this->BusinessModel->where(['id' => $busid])->update(['openid'=>NULL]);

            if($result === FALSE){
                $this->error('解除绑定失败');
                exit;
            }else{
                $this->success('解除账号绑定成功');
                exit;
            }
        }
    }

    // h5和app的账号注册登录
    public function web(){
        if($this->request->isPost()){
            $mobile = $this->request->param('mobile', '','trim');
            $password = $this->request->param('password', '','trim');

            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if($business){
                // 有找到用户，验证密码是否正确
                $repass = md5($password.$business['salt']);

                // 密码不正确
                if($business['password'] != $repass){
                    $this->error('密码不正确');
                    exit;
                }

                $this->success('登陆成功',null,$business);
                exit;
            }else{
                // 没有找到用户，意味着 他在其他平台上没有账号，首次来到小程序
                // Insert 插入语句 顺带将openid 也一并插入进去

                //生成一个密码盐
                $salt = randstr();

                //加密密码
                $password = md5($password.$salt);

                //组装数据
                $data = [
                    'mobile' => $mobile,
                    'nickname' => build_encrypt($mobile, 3, 4, '*'), //脱敏显示
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0', //性别
                    'deal' => '0', //成交状态
                    'money' => '0', //余额
                    'auth' => '0', //邮箱认证
                ];

                //查询出防伪查询的渠道来源的ID信息 数据库查询
                $data['sourceid'] = model('common/Business/Source')->where(['name'=>['LIKE', "%防伪查询%"]])->value('id');

                //执行插入 返回自增的条数
                $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                if($result === FALSE)
                {
                    //失败
                    $this->error($this->BusinessModel->getError());
                    exit;
                }else
                {
                    //查询出当前插入的数据记录
                    $business = $this->BusinessModel->find($this->BusinessModel->id);

                    //注册
                    $this->success('注册成功', null, $business);
                    exit;
                }
            }
        }
    }

    //返回用户的订单商品
    public function product(){
        if($this->request->isPost()){
            $busid = $this->request->param('busid', 0, 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 5, 'trim');
            $keyword = $this->request->param('keyword', '', 'trim');
            $offset = ($page-1)*$limit;

            $where = ['busid' => $busid];

            if(!empty($keyword))
            {
                $where['products.name'] = ['LIKE', "%$keyword%"];
            }

            $list = $this->ProductModel
                ->with(['products'])
                ->where($where)
                ->limit($offset,$limit)
                ->select();

            if($list){
                $this->success('返回列表', null, $list);
                exit;
            }else{
                $this->error('暂无数据');
                exit;
            }
        }
    }

    // 查询验证真假的方法
    public function validator(){
        if($this->request->isPost()){
            $code = $this->request->param('code', 0, 'trim');

            $result = $this->ProductModel->with(['products'])->where(['query_code' => $code])->find();

            if($result === FALSE){
                $this->error('未查询到防伪码信息');
                exit;
            }

            // 更新查询的次数
            $query_num = isset($result['query_num']) ? trim($result['query_num']) :1;
            $query_num++;

            // 更新
            $this->ProductModel->where(['id' => $result['id']])->update(['query_num' => $query_num]) && $result['query_num'] = $query_num;

            $this->success('查询防伪码成功', null, $result);
            exit;


        }
    }

    // 重新生成小程序码
    public function generate(){
        if($this->request->isPost()){
            $code = $this->request->param('code', 0, 'trim');

            $product = $this->ProductModel->with(['products'])->where(['query_code' => $code])->find();

            if(!$product){
                $this->error('防伪码产品不存在');
                exit;
            }

            // 调用EasyWechat实例对象(小程序)来生成小程序码
            $path = "/pages/validate/info?code=$code";

            // 返回生成小程序码的一个文件的二进制流
            $response = $this->app->app_code->get($path);

            $data = [
                'id' => $product['id']
            ];

            // 保存小程序码到文件
            if($response instanceof \EasyWeChat\Kernel\Http\StreamResponse){
                $filename = $response->saveAs('./uploads/wxcode', "$code.png");

                if($filename) $data['query_qrcord'] = "/uploads/wxcode/$filename";
            }

            // 更新数据
            $result = $this->ProductModel->isUpdate(true)->save($data);

            if($result === FALSE){
                $this->error('更换防伪码失败');
                exit;
            }

            $product = $this->ProductModel->with(['products'])->where(['query_code' => $code])->find();

            $this->success('更换防伪码成功', null, $product);
            exit;
        }
    }
}
